from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import request,render_template
from flask import session

from info import constants
from info import db
from info.constants import QINIU_DOMIN_PREFIX
from info.models import Category, News
from info.utils.commons import login_required
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blue

@profile_blue.route('/info')
@login_required
def user_info():
    user = g.user
    if not user:
        return redirect('/')
    return render_template('news/user.html',data={'user':user.to_dict()})


@profile_blue.route('/base_info',methods=['GET','POST'])
@login_required
def base_info():
    '''
    个人中心初步展示：
    1.尝试获取用户信息
    判断请求方式是否为get，是的话直接返回模板
    2.获取传入的参数
    3.判断参数的完整性
    4.检查参数的格式是否正确
    5.更新并保存数据
    6.更新缓存的用户信息

    :return:
    '''
    user = g.user
    if not user:
        return jsonify(errno=RET.USERERR,errmsg='用户未登录')
    if request.method=='GET':
        return render_template('news/user_base_info.html',data={'user':user.to_dict()})
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')
    print(gender)
    if not all([nick_name,signature,gender]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数缺失')
    if gender not in (['MAN','WOMAN']):
        return jsonify(errno=RET.PARAMERR,errmsg='参数格式错误')
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='用户信息保存失败')
    session['nick_name']=user.nick_name
    return jsonify(errno=RET.OK,errmsg='ok')


@profile_blue.route('/pic_info',methods=['GET','POST'])
@login_required
def pic_info():
    '''
    上传头像信息
    1.先尝试获取用户信息
    2，判断用户请求方式，如果是get的话返回模板渲染显示内容
    3.获取参数，读取传过来的图片信息文件
    4.调用七牛云，将图片信息传到七牛云上
    5.拼接存储路径，存储到数据库中
    6.返回路径到ajax中
    :return:
    '''
    user = g.user
    if not user:
        return jsonify(errno=RET.USERERR,errmsg='用户未登录')
    if request.method == 'GET':
        return render_template('news/user_pic_info.html',data={'user':user.to_dict()})
    try:
        avatar_file = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='读取文件错误')
    try:
        url = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='上传图片错误')
    user.avatar_url=url
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存图片信息失败')
    return jsonify(errno=RET.OK,errmsg='OK',data={'avatar_url':QINIU_DOMIN_PREFIX+url})


@profile_blue.route('/pass_info',methods=['GET','POST'])
@login_required
def pass_info():
    '''
    密码修改页面
    1，尝试获取用户信息
    2.判断用户请求方式是get 的话直接返回模板
    3.获取参数
    4.检查参数的完整性
    5.检查旧密码和数据库中的密码是否一致
    6.如果旧密码一致，那么修改数据库中的密码为新密码
    7.返回结果
    :return:
    '''
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
    old_pwd = request.json.get('old_password')
    new_pwd = request.json.get('new_password')
    if not all([old_pwd,new_pwd]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数缺失')
    if not user.check_password(old_pwd):
        return jsonify(errno=RET.DATAERR,errmsg='密码输入错误')
    user.password = new_pwd
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='密码修改失败')
    return jsonify(errno=RET.OK,errmsg='密码修改成功')


@profile_blue.route('/user_follow')
@login_required
def user_follow():
    '''
    用户关注信息列表
    :return:
    '''
    user = g.user
    p = request.args.get('p', 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    follows = []
    current_page = 1
    total_page = 1
    try:
        # 进行分页数据查询
        paginate = user.followed.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取分页数据
        follows = paginate.items
        # 获取当前页数
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    follows_dict = []
    for news in follows:
        follows_dict.append(news)
    data = {
        'follows': follows_dict,
        'total_page': total_page,
        'current_page': current_page
    }
    return render_template('news/user_follow.html',data=data)


@profile_blue.route('/collection')
@login_required
def user_collection():
    '''
    用户收藏新闻信息
    1.尝试获取用户信息
    2.获取参数，默认是1
    3，在数据库中进行分页查询显示
    4.返回数据到模板
    :return:
    '''
    user = g.user
    p = request.args.get('p',1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    collections = []
    current_page = 1
    total_page = 1
    try:
        # 进行分页数据查询
        paginate = user.collection_news.paginate(p,constants.USER_COLLECTION_MAX_NEWS,False)
        # 获取分页数据
        collections = paginate.items
        # 获取当前页数
        current_page = paginate.page
    #     获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    collection_dict = []
    for news in collections:
        collection_dict.append(news)
    data = {
        'collections':collection_dict,
        'total_page':total_page,
        'current_page':current_page
    }
    return render_template('news/user_collection.html',data = data)


@profile_blue.route('/news_release',methods=['GET','POST'])
@login_required
def news_release():
    user = g.user
    categories = []
    try:
        # 获取所有的分类数据
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    # 定义列表保存分类数据
    categories_dicts = []
    for category in categories:
        # 获取字典
        cate_dict = category.to_dict()
        # 拼接内容
        categories_dicts.append(cate_dict)
    # 移除`最新`分类
    categories_dicts.pop(0)
    if request.method == 'GET':
        data = {
             'categories':categories_dicts
        }
        return render_template('news/user_news_release.html',data=data)
    # 获取参数
    title = request.form.get('title')
    source = '个人发布'
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    content = request.form.get('content')
    index_image = request.files.get('index_image')
    if not all([title,category_id,digest,content]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数缺失')
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='新闻图片数据读取异常')
    try:
        url = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='图片上传异常')
    news = News()
    news.title = title
    news.source = source
    news.digest = digest
    news.content = content
    news.category_id = category_id
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + url
    news.user_id = user.id
    news.status = 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='数据上传异常')
    return jsonify(errno=RET.OK,errmsg='新闻发布成功，请等待审核')


@profile_blue.route('/news_list')
@login_required
def news_list():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li,
            "total_page": total_page,
            "current_page": current_page}
    print(news_dict_li)
    return render_template('news/user_news_list.html',data=data)